package com.java.userservice.service.impl;

import com.java.common.model.Result;
import com.java.userservice.dao.UserRoleMapper;
import com.java.userservice.model.UserRole;
import com.java.userservice.model.dto.UserRoleDTO;
import com.java.userservice.service.UserRoleService;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public List<UserRole> list(UserRole userRole) {
        return userRoleMapper.list(userRole);
    }

    @Transactional
    @Override
    public Result save(UserRoleDTO userRoleDTO) {
        // 删除管理员原有的角色
        userRoleMapper.removeByUserId(userRoleDTO.getAdminId());

        // 添加选择角色
        if (!ArrayUtils.isEmpty(userRoleDTO.getRoleIds())) {
            for (Integer roleId : userRoleDTO.getRoleIds()) {
                UserRole userRole = new UserRole();
                userRole.setUserId(userRoleDTO.getAdminId());
                userRole.setRoleId(roleId);
                userRoleMapper.save(userRole);
            }
        }
        return Result.success();
    }
}
